import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import residentRoutes from './routes/residentRoutes.js';
import staffRoutes from './routes/staffRoutes.js';
import medicalRoutes from './routes/medicalRoutes.js';
import activityRoutes from './routes/activityRoutes.js';
import diningRoutes from './routes/diningRoutes.js';
import facilityRoutes from './routes/facilityRoutes.js';

dotenv.config();

const app = express();
const port = process.env.PORT || 3000;

// Middleware
app.use(cors({
  origin: 'http://localhost:5173', // 前端开发服务器地址
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Accept-Charset', 'Authorization'],
  credentials: true
}));
app.use(express.json());

// Routes
app.use('/api/residents', residentRoutes);
app.use('/api/staff', staffRoutes);
app.use('/api/medical', medicalRoutes);
app.use('/api/activities', activityRoutes);
app.use('/api/dining', diningRoutes);
app.use('/api/facility', facilityRoutes);

// Error handling middleware
app.use((err, req, res, next) => {
  console.error('Error details:', {
    message: err.message,
    stack: err.stack,
    path: req.path,
    method: req.method,
    body: req.body
  });
  res.status(500).json({ 
    error: err.message || 'Something went wrong!',
    path: req.path,
    method: req.method
  });
});

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});